package com.example.javaproject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeSet;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Audio.Media;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class Singer extends Activity {
	//设置播放状态为关闭
	boolean isStop;
	boolean flag;
	// 内容提供者
	ListView singerList;
	ListView singerList1;
	ImageView start;
	ImageView pause;
	ImageView stop;
	TextView song;
	int songsPosition;
	int currentPostion;

	// 定义List集合
	ArrayList<String> songList;//存储音乐名
	ArrayList<String> pathList;//存储音乐路径
	TreeSet<String> songSingerTree;//存储歌手(排序+去重)
	ArrayList<String> songSingerList = new ArrayList<String>();//上面TreeSet内容放在这个List里
	ArrayList<String> allSongSingerList = new ArrayList<String>();//歌曲—作者一对一集合
	ArrayList<String> allSongAlbumList = new ArrayList<String>();// 所有歌曲的单独的专辑名

	// 筛选是这个歌手的名字的歌曲加歌曲路径
	ArrayList<String> singerSong = new ArrayList<String>();
	ArrayList<String> songsPath= new ArrayList<String>();
	ArrayList<String> albumName= new ArrayList<String>();
	ArrayList<String> singerName=new ArrayList<String>();
	//设置播放器对象
	MediaPlayer singerMp;
	
	Uri uri = Media.EXTERNAL_CONTENT_URI;
	ContentResolver singerCr;
	ArrayAdapter<String> singerAdapter;//全部歌手集合的Adapter
	ArrayAdapter<String> singerAdapter1;//指定歌手集合的Adapter
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_singer);
		
		// 获取组件对象
		start = (ImageView) findViewById(R.id.singerStart);
		pause = (ImageView) findViewById(R.id.singerPause);
		stop = (ImageView) findViewById(R.id.singerStop);
		singerList = (ListView) findViewById(R.id.singerList);
		singerList1 = (ListView) findViewById(R.id.singerList1);
		song=(TextView) findViewById(R.id.singerMusic);		

		// 对象实例化s
		songList = new ArrayList<String>();// 歌曲名称列表
		pathList = new ArrayList<String>();// 路径列表
		songSingerTree = new TreeSet<String>();// 专辑名称列表	
		
		singerCr = getContentResolver();// 获取内容解析器对象
		singerMp = com.example.javaproject.MainActivity.albumMp;
		
		// 设置监听器
		SingerListener listener = new SingerListener();
		start.setOnClickListener(listener);
		stop.setOnClickListener(listener);
		pause.setOnClickListener(listener);		
		
		// 选择获取歌曲的哪些信息
		String[] columns = { Media.TITLE, Media.DATA, Media.ARTIST, Media.ARTIST, Media.ALBUM};

		Cursor cursor = singerCr.query(uri, columns, null, null, null);
		while (cursor.moveToNext()) {
			songList.add(cursor.getString(0));// 将歌曲名称加入songList
			pathList.add(cursor.getString(1));// 将路径加入pathList
			allSongSingerList.add(cursor.getString(2));// 获得歌曲—作者一对一集合
			songSingerTree.add(cursor.getString(3));// 将歌手加入TreeSet
			allSongAlbumList.add(cursor.getString(4));// 获取所有歌曲单独的专辑名称
		}		
	

		// 将TreeSet放入ArrayList
		for (Iterator iter = songSingerTree.iterator(); iter.hasNext();) {
			songSingerList.add((String) iter.next());
		}
		
		// 四个参数：上下文，ListView每个选项的样式Layout编号，具体样式视图编号，数据列表
		singerAdapter = new ArrayAdapter<String>(Singer.this, R.layout.item,
				R.id.tvItem, songSingerList);
		singerList.setAdapter(singerAdapter);
		
		//点击之前显示第一个音乐
		song.setText(com.example.javaproject.MainActivity.name);	
		
		song.setOnClickListener(listener);
		// 处理ListView的选项点击事件
		singerList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 获取选中的歌手名字
				String albumString = songSingerList.get(position);
				singerSong.clear();
				songsPath.clear();
				albumName.clear();
				singerName.clear();

				for (int i = 0; i < songList.size(); i++) {
					if (allSongSingerList.get(i).equals(albumString)) {
						singerSong.add(songList.get(i));
						songsPath.add(pathList.get(i));
						albumName.add(allSongAlbumList.get(i));
						singerName.add(allSongSingerList.get(i));
					}
				}
				
				singerAdapter1 = new ArrayAdapter<String>(Singer.this,
						R.layout.item, R.id.tvItem, singerSong);
				singerList1.setAdapter(singerAdapter1);
				
				// 处理点击事件播放音乐
				singerList1.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						//----------------------------------------------------------------------------------------------------------
						 PrintWriter pw = null;
	                        BufferedReader br = null;
	                        //创建一个文件用于记录歌曲播放时间
	                        File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + singerSong.get(position) + ".txt");
	                        //如果文件不存在，也就是第一次播放该歌曲
	                        try {

	                            if (!file.exists()) {
	                                //初始化字符输出流
	                                pw = new PrintWriter(new FileOutputStream(file));
	                                //设置初始播放次数为1
	                                pw.write("1");
	                                pw.flush();//刷新缓冲区


	                            } else {
	                                //文件存在，也就是以前播放过该歌曲

	                                //用于读文件
	                                br = new BufferedReader(new FileReader(file));
	                                //先读取以前的播放次数
	                                String count = br.readLine();

	                                //用于写文件
	                                pw = new PrintWriter(new FileOutputStream(file));
	                                //重新写入文件 设置新的播放次数为原来次数+1
	                                pw.println((Integer.parseInt(count) + 1) + "");
	                                pw.flush();//刷新缓冲区

	                            }
	                        } catch (Exception e) {
	                            e.printStackTrace();
	                        }
						//-----------------------------------------------------------------------------------------------------------

						
						songsPosition=position;
						
						//正在播放的歌曲的名称
						com.example.javaproject.MainActivity.name=singerSong.get(position);
						song.setText(com.example.javaproject.MainActivity.name);
						try {
							singerMp.reset();// 每次重置MediaPlayer，然后才能重新指定资源
							// 设置数据源，从pathList获取position位置的歌曲的路径
							singerMp.setDataSource(songsPath.get(position));
							singerMp.prepare();
							singerMp.start();
							isStop = false;
						} catch (Exception e) {
							Log.e("SingerActivity", e.getMessage());
						}
					}
				});

			}
		});		
		
	}
		
	@Override
	protected void onResume(){
		super.onResume();
		song.setText(com.example.javaproject.MainActivity.name);
		isStop=com.example.javaproject.MainActivity.isStop;
	}
	
	// 监听器
	class SingerListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.singerStart:
    			Toast t3=Toast.makeText(Singer.this,"上一首",Toast.LENGTH_SHORT);
    			t3.show(); 
				if(songsPosition>=1&&songsPosition<=singerSong.size()){

					try {
						song.setText(singerSong.get(songsPosition-1));
						singerMp.reset();
						singerMp.setDataSource(songsPath.get(songsPosition-1));
						songsPosition=songsPosition-1;
						singerMp.prepare();
						singerMp.start();
					} catch (IOException e) {
						e.printStackTrace();
					}
    			}else{
					try {
						song.setText(songList.get(singerSong.size()-1));
						singerMp.reset();
						singerMp.setDataSource(songsPath.get(singerSong.size()-1));
						songsPosition=singerSong.size()-1;
						singerMp.prepare();
						singerMp.start();
					} catch (IOException e) {
						e.printStackTrace();
					}
    			}
				break;
			case R.id.singerPause:
				if(!isStop){
					pause.setImageDrawable(getResources().getDrawable(R.drawable.start));
	    			Toast t2=Toast.makeText(Singer.this,"已暂停",Toast.LENGTH_SHORT);
	    			t2.show(); 
	    			singerMp.pause();
					isStop = true;
					flag=isStop;
				}else {
					pause.setImageDrawable(getResources().getDrawable(R.drawable.pause));
					singerMp.start();
	    			Toast t1=Toast.makeText(Singer.this,"播放",Toast.LENGTH_SHORT);
	    			t1.show(); 
	    			isStop = false;
					flag=isStop;
				}
				break;
			case R.id.singerStop:
    			Toast t4=Toast.makeText(Singer.this,"下一首",Toast.LENGTH_SHORT);
    			t4.show(); 
				if(songsPosition>=0&&songsPosition<=singerSong.size()-2){

					try {
						song.setText(singerSong.get(songsPosition+1));
						singerMp.reset();
						singerMp.setDataSource(songsPath.get(songsPosition+1));
						songsPosition=songsPosition+1;
						singerMp.prepare();
						singerMp.start();
					} catch (IOException e) {
						e.printStackTrace();
					}
    			}else{
					try {
						song.setText(singerSong.get(0));
						singerMp.reset();
						singerMp.setDataSource(songsPath.get(0));
						songsPosition=0;
						singerMp.prepare();
						singerMp.start();
					} catch (IOException e) {
						e.printStackTrace();
					}
    			}
				break;
			case R.id.singerMusic:
				currentPostion=singerMp.getCurrentPosition();
				Intent individual1=new Intent(Singer.this,IndividualSongs.class);
				individual1.putExtra("albumName",albumName.get(songsPosition));
				individual1.putExtra("songsName", singerSong.get(songsPosition));
				individual1.putExtra("singerName", singerName.get(songsPosition));
				individual1.putExtra("songsPath", songsPath.get(songsPosition));
				individual1.putExtra("currentPostion", currentPostion);
				individual1.putExtra("flag",flag);
				startActivity(individual1);
				break;
			}
		}
	}
}